package com.zhx.real.security.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhanghaixuan
 * @create 2017/11/26-下午10:16
 **/
public class AbstractSessionStrategy {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 跳转前是否创建新的session
     */
    private boolean createNewSession = true;

    private ObjectMapper objectMapper = new ObjectMapper();

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	private static final String STATIC_JS = ".js";
	private static final String STATIC_CSS = ".css";
	private static final String STATIC_JSON = ".json";
	private static final String STATIC_PNG = ".png";
	private static final String STATIC_JPG = ".jpg";
	private static final String STATIC_SPIRT = "/";

	/**

	 */
	public AbstractSessionStrategy() {
	}

	protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {

		if(createNewSession) {
			request.getSession();
		}

		String sourceUrl = request.getRequestURI();

		logger.info("引发跳转的url是" + sourceUrl);

		if(StringUtils.endsWithIgnoreCase(sourceUrl, STATIC_JS) || StringUtils.endsWithIgnoreCase(sourceUrl, STATIC_CSS)
				|| StringUtils.endsWithIgnoreCase(sourceUrl, STATIC_JSON) || StringUtils
				.endsWithIgnoreCase(sourceUrl, STATIC_PNG) || StringUtils.endsWithIgnoreCase(sourceUrl, STATIC_JPG)) {
			redirectStrategy.sendRedirect(request, response, sourceUrl);
			return;
		}

		String contextPath = request.getContextPath();

		if(contextPath.equals(sourceUrl) || sourceUrl.equals(contextPath + STATIC_SPIRT)) {
			//首页跳转问题  直接重定向到  根目录下
			redirectStrategy.sendRedirect(request, response, STATIC_SPIRT);
		}

		Object result = buildResponseContent(request);
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(objectMapper.writeValueAsString(result));
	}

	/**
	 * @param request
	 * @return
	 */
	protected String buildResponseContent(HttpServletRequest request) {
		String message = "身份失效,请重新登录!";
		if(isConcurrency()) {
			message = message + "，有可能是并发登录导致的";
		}
		return message;
	}

    /**
     * session失效是否是并发导致的
     * @return
     */
    protected boolean isConcurrency() {
        return false;
    }


    public void setCreateNewSession(boolean createNewSession) {
        this.createNewSession = createNewSession;
    }
}
